package com.zhiliao.intermediary.demo3;

import java.util.ArrayList;
import java.util.List;

public class IntermediaryTest {
    public static void main(String[] args) {
        Customer a = new A("xiao A");
        Customer b = new B("xiao B");
        Customer c = new C("xiao C");

        Medium medium = new Medium();
        medium.registerCustomer(a);
        medium.registerCustomer(b);
        medium.registerCustomer(c);

        medium.relay(a,"xiao B","hello xiao B");

    }
}

abstract class Customer{
    protected Medium medium;
    private String name;
    abstract void send(String targetName,String message);
    abstract void receive(String sourceName,String message);

    public void callMedium(Medium medium) {
        this.medium = medium;
    }

    public Customer(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

class Medium{
    private List<Customer> customerList = new ArrayList<>();

    protected void registerCustomer(Customer customer) {
        if (!customerList.contains(customer)) {
            customerList.add(customer);
            customer.callMedium(this);
        }
    }

    protected void relay(Customer src,String targetName, String message) {
        for (Customer customer : customerList) {
            if (customer.getName().equals(targetName)) {
                customer.receive(src.getName(), message);
            }
        }
    }

}
class A extends Customer{
    public A(String name) {
        super(name);
    }

    @Override
    void send(String targetName, String message) {
        System.out.println("a send");
        medium.relay(this,targetName,message);
    }

    @Override
    void receive(String sourceName, String message) {
        System.out.println(this.getName()+"收到來自-"+sourceName+"-的消息~");
    }
}
class B extends Customer{
    public B(String name) {
        super(name);
    }

    @Override
    void send(String targetName, String message) {
        System.out.println("b send");
        medium.relay(this,targetName,message);
    }

    @Override
    void receive(String sourceName, String message) {
        System.out.println(this.getName()+"收到來自-"+sourceName+"-的消息~");
    }
}
class C extends Customer{
    public C(String name) {
        super(name);
    }

    @Override
    void send(String targetName, String message) {
        System.out.println("c send");
        medium.relay(this,targetName,message);
    }

    @Override
    void receive(String sourceName, String message) {
        System.out.println(this.getName()+"收到來自-"+sourceName+"-的消息~");
    }
}